package cn.masterj.springcloud.controller;

import cn.masterj.springcloud.service.fallback.BlockFallbackFactory;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author masterJ
 * @create 2020-04-18 13:37
 */
@RestController
public class SentielController {

    static {
        // 手动设置系统限流规则
        List<SystemRule> rules = new ArrayList<>();
        SystemRule rule = new SystemRule();
        rule.setQps(3);
        rules.add(rule);
        SystemRuleManager.loadRules(rules);
    }

    /**
     * @return
     */
    @SentinelResource(value = "testB", blockHandler = "blockException", fallback = "fallbackException")
    @GetMapping("/consumer/testB")
    public String testB(){
        return "直接返回testB，不通过feign去远程调用，测试SentinelResource的blockHandler,   测试流控规则";
    }

    /**
     * @return
     */
    @SentinelResource(value = "testB", blockHandler = "blockException", fallback = "fallbackException")
    @GetMapping("/consumer/testC")
    public String testC(Long id){
        return "直接返回testCC，不通过feign去远程调用，测试SentinelResource的blockHandler,   测试流控规则";
    }

    @SentinelResource(value = "testE", blockHandler = "blockHandler" , blockHandlerClass = BlockFallbackFactory.class,fallback = "fallbackHandler", fallbackClass = BlockFallbackFactory.class)
    @GetMapping("/consumer/testE")
    public String testE(Long id){
        if (id < 0){
            throw new IllegalArgumentException("非法参数异常");
        }
        return "直接返回testE，测试SentinelResource的blockHandler，   测试异常导致服务降级";
    }

    @SentinelResource(value = "testF", defaultFallback = "fallbackException")
    @GetMapping("/consumer/testF")
    public String testF(long id){
        if (id < 0){
            throw new IllegalArgumentException("非法参数异常");
        }
        return "直接返回testFFFFFFFFFF， defaultFallback,参数为空，或只有一个Throwable参数  测试defaultFallback和热点参数规则";
    }


    public String blockException(BlockException e){
        System.out.println("-------------同一个方法内----------BlockException------" );
        e.printStackTrace();
        return "同一个方法内-===========BlockException;;;\t" + e.getRule();
    }

    public String fallbackException(Throwable e){
        System.out.println("-------------同一个方法内----------fallbackException------" );
        e.printStackTrace();
        return "同一个方法内-===========fallbackException;;;\t" + e.getMessage();
    }

}
